package com.probiz.estore.webapp.util;

import javax.servlet.http.HttpServletResponse;

public class ResponseUtil {
	private static final String HEADER_PRAGMA = "Pragma";

	private static final String HEADER_EXPIRES = "Expires";

	private static final String HEADER_CACHE_CONTROL = "Cache-Control";
	/**
	 * Set HTTP headers to allow caching for the given number of seconds.
	 * Tells the browser to revalidate the resource if mustRevalidate is
	 * <code>true</code>.
	 * @param response the current HTTP response
	 * @param seconds number of seconds into the future that the response
	 * should be cacheable for
	 */
	public static void cacheForSeconds(HttpServletResponse response, int seconds) {
		// HTTP 1.0 header
		response.setDateHeader(HEADER_EXPIRES, System.currentTimeMillis() + seconds * 1000L);
		// HTTP 1.1 header
		String headerValue = "max-age=" + seconds;
		headerValue += ", must-revalidate";
		
		response.setHeader(HEADER_CACHE_CONTROL, headerValue);
	}

	/**
	 * Prevent the response from being cached.
	 * See <code>http://www.mnot.net/cache_docs</code>.
	 */
	public static void preventCaching(HttpServletResponse response) {
		response.setHeader(HEADER_PRAGMA, "no-cache");
		// HTTP 1.0 header
		response.setDateHeader(HEADER_EXPIRES, 1L);
		// HTTP 1.1 header: "no-cache" is the standard value,
		// "no-store" is necessary to prevent caching on FireFox.
		response.setHeader(HEADER_CACHE_CONTROL, "no-cache");
		response.addHeader(HEADER_CACHE_CONTROL, "no-store");
	}

	/**
	 * Apply the given cache seconds and generate respective HTTP headers.
	 * <p>That is, allow caching for the given number of seconds in the
	 * case of a positive value, prevent caching if given a 0 value, else
	 * do nothing (i.e. leave caching to the client).
	 * @param response the current HTTP response
	 * @param seconds the (positive) number of seconds into the future that
	 * the response should be cacheable for; 0 to prevent caching; and
	 * a negative value to leave caching to the client.
	 */
	public static void applyCacheSeconds(HttpServletResponse response, int seconds) {
		if (seconds > 0) {
			cacheForSeconds(response, seconds);
		}
		else if (seconds == 0) {
			preventCaching(response);
		}
		// Leave caching to the client otherwise.
	}
}
